// 有兼容性的问题
if (typeof window == 'undefined' || typeof Promise == 'undefined') {
  console && console.error('有兼容性的问题或者不支持Promise语法!')
  return false
}
// ajax promise 形式 ajax({url: 'xxx',data: {id: '233'} }).then((res)=>{}).catch((err)=>{})
const requst = function(opt) {
  if (typeof Promise == 'undefined') {
    console.log('您的浏览器不支持Promise!')
    return true
  }
  return new Promise(function(resolve, reject) {
    opt = opt || {}
    opt.method = opt.method ? opt.method.toUpperCase() : 'GET'
    opt.url = opt.url || ''
    opt.async = opt.async || true
    opt.data = opt.data || null
    let xmlHttp = new XMLHttpRequest()
    let params = []
    for (let key in opt.data) {
      params.push(key + '=' + opt.data[key])
    }
    let postData = params.join('&')
    if (opt.method.toUpperCase() === 'POST') {
      xmlHttp.open(opt.method, opt.url, opt.async)
      xmlHttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded;charset=utf-8')
      xmlHttp.send(postData)
    } else if (opt.method.toUpperCase() === 'GET') {
      xmlHttp.open(opt.method, opt.url + '?' + postData, opt.async)
      xmlHttp.setRequestHeader('Content-Type', 'application/json;charset=utf-8')
      xmlHttp.send(null)
    }
    xmlHttp.onreadystatechange = function() {
      if (xmlHttp.readyState == 4) {
        if (xmlHttp.status == 200) {
          resolve(JSON.parse(xmlHttp.responseText || {}))
        } else {
          reject(xmlHttp.responseText)
        }
      }
    }
  })
}
export default requst
